package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    /**
     * 查看探店笔记
     *
     * @param id
     * @return
     */
    @Override
    public Result getByBlogId(Long id) {
        // 查询blog
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        // 查询blog的user
        User user = userService.getById(blog.getUserId());
        // 补充blog的user属性
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        // 查询blog是否被点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 给笔记点赞
     *
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 判断用户是否点赞
        String key = "blog:liked:" + id;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        // 如果未点赞，数据库 + 1
        if (BooleanUtil.isFalse(isMember)) {
            boolean success = this.update().setSql("liked = liked + 1").eq("id", id).update();
            if (success) {
                // 用户保存到redis的set集合
                stringRedisTemplate.opsForSet().add(key, userId.toString());
            }
        } else {
            // 点赞，数据库 - 1
            boolean success = this.update().setSql("liked = liked - 1").eq("id", id).update();
            // 将用户从redis中移除
            if (success) {
                stringRedisTemplate.opsForSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 笔记分页查询
     *
     * @param current
     * @return
     */
    @Override
    public Result page(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            // 查询blog是否被点过赞
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success = this.save(blog);
        if (!success) {
            return Result.fail("新增笔记失败");
        }
        // 查询博主所有粉丝 select * from tb_follow where follow_user_id = user.getId()
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 将笔记id发送给所有粉丝
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    private void isBlogLiked(Blog blog) {
        // 获取当前用户id
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return;
        }
        Long userId = user.getId();

        // 判断用户是否点赞
        String key = "blog:liked:" + blog.getId();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if (BooleanUtil.isTrue(isMember)) {
            blog.setIsLike(true);
        }
    }

    /**
     * 滚动分页查询
     *
     * @return
     */
    @Override
    @Transactional
    public Result followScrollQuery(Long max, Integer offset) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 查询收件箱 zrevrangebyscore key max min limit offset count
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, max, 0, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.fail("没有笔记");
        }

        // 解析出blogId，minTime，offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 获取blogId
            String idStr = typedTuple.getValue();
            blogIds.add(Long.valueOf(idStr));
            // 获取minTime，即集合最后一个元素
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        String idStr = StrUtil.join(",", blogIds);
        // 根据blogId查询blog
        List<Blog> blogs = this.query().in("id", blogIds).last("order by field(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            // 查询blog的user
            User user = userService.getById(blog.getUserId());
            // 补充blog的user属性
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            // 查询blog是否被点过赞
            isBlogLiked(blog);
        }
        // 封装数据
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
